package com.MutiModule.alexgaoyh.upload.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.MutiModule.alexgaoyh.upload.constants.CORSConstants;

/**
 * 跨域问题
 * @author alexgaoyh
 *
 */
public class CORSFilter implements Filter{

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws ServletException, IOException {
    	
    	// 获得在下面代码中要用的request,response,session对象
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        
        //从配置文件中匹配允许跨域访问的请求链接，对此请求链接进行允许访问
        String cliRequest = servletRequest.getHeader("Origin");
        String Access_Control_Allow_Origin_s =  CORSConstants.getAccess_Control_Allow_Origin();
        for(String str : Access_Control_Allow_Origin_s.split(",")){
     	   if(str.equals(cliRequest)){
     		   servletResponse.addHeader("Access-Control-Allow-Origin", "*");
     	   }
        }

        if(servletRequest.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(servletRequest.getMethod())) {
        	servletResponse.addHeader("Access-Control-Allow-Methods", "HEAD,GET,POST,PUT,DELETE,OPTIONS");
        	servletResponse.addHeader("Access-Control-Allow-Headers", "Content-Type,Origin,Accept");
        	servletResponse.addHeader("Access-Control-Max-Age", "120");
        }

        chain.doFilter(request, response);
    }

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
}